/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.group4.controller;

import com.group4.entity.Admin;
import com.group4.entity.Admin_;
import com.group4.entity.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author andake, anjonas
 */
@Stateless
public class AdminFacade extends AbstractFacade<Admin> {
    @PersistenceContext(unitName = "HighSchoolPortal_pu")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public AdminFacade() {
        super(Admin.class);
    }
    
    public Admin findByLogin(String username, String password) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Admin> cq = builder.createQuery(Admin.class);
        
        Root<Admin> query = cq.from(Admin.class);
        Join<Admin,User> adminUser = query.join(Admin_.userInfo);
        
        Path<String> uname = adminUser.get("login");
        Path<String> p = adminUser.get("password");
                
        Predicate userCond = builder.equal(uname, username);
        Predicate passCond = builder.equal(p, password);
        cq.where(builder.and(userCond, passCond));
        TypedQuery<Admin> a = em.createQuery(cq);
        List<Admin> adminList = a.getResultList();
        if(adminList.size() > 0)
            return adminList.get(0);
        else
            return null;
    }
}
